import http from '@ohos.net.http';
import data_storage from '@ohos.data.storage';

const BASE_URL = 'http://117.78.16.25:5551/api';

export default {
    get(url, fn) {
        let options = this.setHttpRequestOptions(http.RequestMethod.GET, null);
        http.createHttp().request(BASE_URL + url, options, (err, data) => {
            if (!err) {
                console.info('Result:' + data.result);
                fn(JSON.parse(data.result));
            } else {
                console.info('error:' + JSON.stringify(err));
            }
        });

    },
    post(url, param, fn) {
        let options = this.setHttpRequestOptions(http.RequestMethod.POST, param);
        http.createHttp().request(BASE_URL + url, options, (err, data) => {
            if (!err) {
                console.info('Result:' + data.result);
                fn(JSON.parse(data.result));
            } else {
                console.info('error:' + JSON.stringify(err));
            }
        });
    },
    setHttpRequestOptions(method, param) {
        let options = {
            method: method, // 可选，默认为“GET”
            header: {
                'Content-Type': 'application/json',
                'token': this.getToken(),
                'client_type': 'harmonyos' // 区分客户端类型
            }
        };
        if (method == http.RequestMethod.POST) {
            options.extraData = param;
        }
        return options;
    },

    getToken() {
        let token = getApp().globalData.token;
        console.info('GET token from app.js : ' + token)
        if (token == null || token == undefined || token == '') {
            token = data_storage.getStorageSync(getApp().globalData.path).getSync('token', 'noToken');
            console.info('GET token from data_storage : ' + token)
        }
        return token;
    }
}